#include "ipc_header.hpp"
using namespace std;
int main()
{
    // key
    key_t key = creat_key();
    if (key < 0)
    {
        cout << "生成key失败" << endl;
        exit(5);
    }
    // get
    int shm_id = shmget(key, shm_size, IPC_CREAT | 0777);
    if (shm_id == -1)
    {
        log() << "获取共享内存失败 key: " << key << endl;
        exit(2);
    }
    else
        log() << "成功获取共享内存 shm_id: " << shm_id << endl;
    // attach

    char *shm = reinterpret_cast<char *>(shmat(shm_id, nullptr, 0));
    if (shm == reinterpret_cast<char *>(-1))
    {
        log() << "关联共享内存失败 shm_id:" << shm_id << endl;
        exit(3);
    }
    else
        log() << "成功关联共享内存！ shm_id:" << shm_id << endl;
    // use
    // unsafe
    // while(true){
    //     cout<<"请输入:> ";
    //     cout.flush();
    //     ssize_t read_ret=read(0,shm,shm_size-1);
    //     shm[read_ret]=0;
    //     if(strcmp(shm,"_exit\n")==0)
    //         break;
    //     sleep(1);
    // }
    // safe
    // use pipe to ctrl
    int pipe_fd = get_pipe(pipe_for_client);
    if (pipe_fd < 0)
    {
        log() << "获取管道失败！" << endl;
        exit(3);
    }
    else
        log() << "获取管道成功" << endl;
    *shm=0;
    while (strcmp(shm, "_exit\n") != 0)
    {
        cout << "请输入:> ";
        cout.flush();
        ssize_t read_ret = read(0, shm, shm_size - 1);
        shm[read_ret] = 0;
        ipc_signal(pipe_fd);
    }
    close(pipe_fd);
    // detach
    int dt_shm_ret = shmdt(shm);
    if (dt_shm_ret == -1)
    {
        log() << "去关联失败 shm_id:" << shm_id << endl;
        exit(3);
    }
    else
        log() << "去关联成功 shm_id:" << shm_id << endl;
    return 0;
}